/*
 * Copyright (C) 2010-2014 Enrique Lara (enrique.posix2.lara@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package app.transittool.model;

import android.content.Context;
import android.content.Intent;

import android.database.Cursor;

import android.net.Uri;

import app.transittool.Android;
import app.transittool.R;

import app.transittool.provider.Projections;

import app.transittool.util.Constants;
import app.transittool.util.Log;

import trs.unknown.UnknownAgency;

import trs.wmata.BusAgency;
import trs.wmata.TrainAgency;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Properties;

public final class App {
    private static final String TAG = "App";
    private static Properties config = null;
    private static final int[][] AGENCY_ID_TO_NAME_MAP = {
                                                             new int[] {
                                                                 TrainAgency.WMATA_TRAIN_AGENCY_ID,
                                                                 R.string.agency_wmata_train
                                                             },
                                                             new int[] {
                                                                 BusAgency.WMATA_BUS_AGENCY_ID,
                                                                 R.string.agency_wmata_bus
                                                             }
    };
    private static ArrayList<String> debugMessages = new ArrayList<String>();

    private App() {
    }

    public static boolean isDebug() {
        return Constants.DEBUG;
    }

    public static ArrayList<String> getDebugMessages() {
        return debugMessages;
    }

    public static void showDebug(final Context c, final String msg) {
        Log.d(TAG, msg);

        if (!isDebug()) {
            return;
        }

        Android.showLongToast(c, msg);
    }

    public static void showError(final Context c, final String msg, final Throwable t) {
        try {
            final StringWriter sw = new StringWriter();
            final PrintWriter writer = new PrintWriter(sw);
            writer.print(msg);

            if (isDebug()) {
                t.printStackTrace(writer);
            }

            Android.showLongToast(c, sw.toString());

            Log.e(TAG, msg, t);

            if (isDebug()) {
                debugMessages.add(sw.toString());
            }
        } catch (final Throwable t1) {
            throw new InconceivableException(c, R.string.show_error_failed_exception, t1);
        }
    }

    public static int[][] getAgencyIdToNameIdMap(final Context context) {
        return AGENCY_ID_TO_NAME_MAP;
    }

    public static Agency getAgency(final int agencyId, final Context context) {
        switch (agencyId) {
            case TrainAgency.WMATA_TRAIN_AGENCY_ID:
                return TrainAgency.getInstance(context);

            case BusAgency.WMATA_BUS_AGENCY_ID:
                return BusAgency.getInstance(context);

            default:
                return new UnknownAgency(context);
        }
    }

    public static ArrayList<Alarm> loadAllAlarms(final Cursor cursor, final Context context, final int agencyIdIndex) {
        final ArrayList<Alarm> alarms = new ArrayList<Alarm>(10);

        if ((cursor != null) && cursor.moveToFirst()) {
            do {
                alarms.add(loadAlarm(cursor, context, agencyIdIndex));
            } while (cursor.moveToNext());
        }

        return alarms;
    }

    public static Alarm loadAlarm(final Cursor cursor, final Context context, final int agencyIdIndex) {
        int agencyId = -1;

        if ((cursor != null) && (agencyIdIndex > 0)) {
            agencyId = cursor.getInt(Projections.AlarmsAll.AGENCY_ID);
        }

        final Agency agency = getAgency(agencyId, context);

        return agency.loadAlarm(cursor);
    }

    public static Alarm loadAlarm(final Uri uri, final Context context) {
        Alarm a = null;

        final Cursor cursor = context.getContentResolver().query(uri, Projections.AlarmsAll.PROJECTION, null, null, null);

        if ((cursor != null) && cursor.moveToFirst()) {
            a = App.loadAlarm(cursor, context, Projections.AlarmsAll.AGENCY_ID);
            cursor.close();
        } else {
            throw new InconceivableException(context, R.string.item_access_exception, uri);
        }

        return a;
    }

    public static Properties getConfig(final Context context) {
        if (config == null) {
            initConfig(context);
        }

        return config;
    }

    private static synchronized void initConfig(final Context context) {
        InputStream is = null;
        BufferedReader reader = null;

        config = new Properties();

        try {
            is = context.getResources().openRawResource(R.raw.app);
            reader = new BufferedReader(new InputStreamReader(is));

            String str = null;

            while ((str = reader.readLine()) != null) {
                if (str.length() == 0) {
                    continue;
                }

                final String[] toks = str.split("=");

                if ((toks != null) && (toks.length == 2)) {
                    config.put(toks[0], toks[1]);
                }
            }
        } catch (final IOException e) {
            throw new InconceivableException(context, R.string.config_parsing_exception, e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    if (Log.isDebugEnabled(TAG)) {
                        Log.d(TAG, "Ignore Exception", e);
                    }
                }
            }
        }
    }

    public static boolean gotoEdit(final Uri uri, final Context context) {
        context.startActivity(new Intent(Constants.ACTION_EDIT, uri));

        return true;
    }

    public static Agency[] getAllAgencies(final Context ctx) {
        return new Agency[] {
                   getAgency(TrainAgency.WMATA_TRAIN_AGENCY_ID, ctx),
                   getAgency(BusAgency.WMATA_BUS_AGENCY_ID, ctx)
               };
    }
}
